﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Pay.Core;
using Pay.Data;
using Pay.DTO;
using Pay.IService;
using Pay.Service.Cache;
using Pay.TO;

namespace Pay.Service.Service {
    public class ShippingPositionService : ServiceBase, IShippingPositionService {
        private IUnitOfWork _iUnitOfWork;
        public ShippingPositionService(IUnitOfWork iUnitOfWork)
                     : base(iUnitOfWork) {
            _iUnitOfWork = iUnitOfWork;
        }
        public PagedResult<shipping_position_dto> Get(ShippingPositionQuery query) {
            Expression<Func<ShippingPosition, bool>> filter = c => true;
            //if (!string.IsNullOrEmpty(query.name))
            //    filter = filter.And(c => c.Title.Contains(query.name));
            return context.ShippingPosition.FromCachePaged<ShippingPosition, shipping_position_dto>(query.page, query.size, filter, orderBy => orderBy.OrderByDescending(c => c.Id));
        }

        public shipping_position_dto Get(long id) {
            var query = context.ShippingPosition.Where(c => c.Id == id);
            return query.FromCacheFirstOrDefault<ShippingPosition, shipping_position_dto>();
        }


        public int Delete(List<long> ids) {
            foreach (var id in ids)
                context.ShippingPosition.Remove(id);
            int result = _iUnitOfWork.Commit();
            return result;
        }

        /// <summary>
        /// 保存/修改配送网点
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// 
        public int Save(shipping_position_dto model) {
            if (model.id == 0) {
                context.ShippingPosition.Add(model.ToDtoObject<ShippingPosition>());
            } else {
                var shipping = context.ShippingPosition.Where(c => c.Id == model.id).FirstOrDefault();
                shipping.MerchantId = model.merchant_id;
                shipping.Name = model.name;
                shipping.ShopName = model.shop_name;
                shipping.RegionId = model.region_id;
                shipping.Phone = model.phone;
                shipping.Address = model.address;
            }

            int result = _iUnitOfWork.Commit();
            return result;
        }
        /// <summary>
        /// 获取商户配送网点
        /// </summary>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public List<shipping_position_dto> GetByUser(long user_id) {
            var positions = context.ShippingPosition.Where(c => c.MerchantId == user_id).FromCache<ShippingPosition, shipping_position_dto>();
            return positions;
        }
    }
}
